<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;
use app\traits\MyModelTrait;

/**
 * @mixin \think\Model
 */
class AdminMenu extends Model
{
    use MyModelTrait;

    // 菜单表
    protected $table = 'admin_menu';

    const FIELDS = [
        // 是否在菜单中显示
        'is_show'   => [0 => '否', 1 => '是']
    ];

    /**
     * 生成记录
     *
     * @param int    $pid
     * @param int    $rank
     * @param string $title
     * @param string $uri
     * @param int    $is_show
     */
    public static function generateLog(
        int     $pid,
        int     $rank,
        string  $title,
        string  $uri,
        int     $is_show = 1
    ): void{
        $insert = [
            'pid'           => $pid,
            'rank'          => $rank,
            'title'         => $title,
            'uri'           => $uri,
            'is_show'       => $is_show,
            'created_at'    => date('Y-m-d H:i:s'),
            'updated_at'    => date('Y-m-d H:i:s')
        ];
        self::insert($insert);
    }// generateLog() end

    /**
     * 获取所有的上级菜单
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAllPid(): array
    {
        return self::field('id,title')->where('pid', 0)->where('is_show', 1)->order('rank', 'DESC')->select()->toArray();
    }

    /**
     * 删除子菜单
     *
     * @param int $pid  admin_menu.id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function deleteChildMenu(int $pid)
    {
        $menus = self::whereRaw('pid = :pid', ['pid' => $pid])->select();
        foreach($menus as $menu){
            $admin_menu_pid = (int)$menu->id;
            $menu->delete();
            self::deleteChildmenu($admin_menu_pid);
        }
    }// deleteChildMenu() end
}
